﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

/// <summary>
/// http://codekata.com/kata/kata04-data-munging/
/// </summary>
namespace RandomKatas.Kata04
{
    public class DataMunging
    {
        public Tuple<int, double> Weather_SmallestSpread(string weatherFileContents)
        {
            double minSpread = double.MaxValue;
            Func<string[], bool> evalLine = cols =>
            {
                if (cols.Length < 3) return false;
                var maxT = double.Parse(cols[1].Trim('*'));
                var minT = double.Parse(cols[2].Trim('*'));
                if (maxT - minT < minSpread)
                {
                    minSpread = maxT - minT;
                    return true;
                }

                return false;
            };

            var best = FindWinningLine(weatherFileContents, 2, evalLine);
            return Tuple.Create(int.Parse(best[0]), minSpread);
        }

        public Tuple<string, int> Football_SmallestSpread(string footballFileContents)
        {
            int minSpread = int.MaxValue;
            Func<string[], bool> evalLine = cols =>
            {
                if (cols.Length < 9) return false;
                var goalsFor = int.Parse(cols[6]);
                var goalsAgainst = int.Parse(cols[8]);
                var curSpread = Math.Abs(goalsFor - goalsAgainst);
                if (curSpread < minSpread)
                {
                    minSpread = curSpread;
                    return true;
                }

                return false;
            };

            var winning = FindWinningLine(footballFileContents, 1, evalLine);
            return Tuple.Create(winning[1].Trim(), minSpread);
        }

        private string[] FindWinningLine(string fullFile, int skipHeaderLines, Func<string[], bool> evalLine)
        {
            string[] best = null;
            var lines = fullFile.Split('\n');
            for (int idx=skipHeaderLines; idx < lines.Length; ++idx)
            {
                var line = lines[idx];
                var cols = line.Split((char[])null, StringSplitOptions.RemoveEmptyEntries);
                try
                {
                    if (evalLine(cols))
                        best = cols;
                } catch (Exception e)
                {
                    Trace.TraceWarning("Ignoring [{0}] - {1}", line, e.Message);
                }
            }

            return best;
        }
    }
}
